<template>
	<view>
		<view class="w-full text-center">
			<text class="">登录</text>
		</view>
		<view class="p-4">
			<uv-form ref="formRef" :model="entity" :rules="rules" labelPosition="left" labelWidth="5rem">
				<uv-form-item label="用户名" prop="username" borderBottom>
					<uv-input v-model="entity.username" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="密码" prop="password" borderBottom>
					<uv-input v-model="entity.password" type="password" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="验证码" prop="verifyCode" borderBottom>
					<uv-input v-model="entity.verifyCode" border="none">
						<template v-slot:suffix>
							<image :src="verifyCodeUrl" class="w-[120px] h-[40px]" @click="updateVerifyCode"></image>
						</template>
					</uv-input>
				</uv-form-item>
				<view class="my-2 w-full flex justify-between">
					<uv-checkbox-group @change="(detail) => { rememberMe = detail && detail.length > 0; }">
						<uv-checkbox label="记住密码" name="rememberMe" checked></uv-checkbox>
					</uv-checkbox-group>

					<navigator @click="forgetPassword">
						<uv-text type="primary" text="忘记密码"></uv-text>
					</navigator>
				</view>
				<view class="my-2 w-full">
					<uv-button type="primary" text="登录" @click="login"></uv-button>
				</view>
				<view class="my-2 w-full">
					<uv-button text="注册" @click="register"></uv-button>
				</view>
			</uv-form>
		</view>
		<view>
			<uv-notify ref="notify"></uv-notify>
		</view>
	</view>
</template>

<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, getCurrentInstance } from 'vue';
import authService from "@/services/auth.service";
import personalCenterService from "@/services/personal-center.service";
import { UNI_STORAGE_KEY_REMEMBER_ME, UNI_STORAGE_KEY_TOKEN, UNI_STORAGE_KEY_USER_PROFILE } from '@/utils/constants';
import { onLoad } from "@dcloudio/uni-app";

const entity = ref({
	username: '',
	password: '',
	verifyCode: '',
});
const verifyCodeUrl = ref("");
const formRef = ref();
const rememberMe = ref(true);
const loading = ref(false);

const notify = ref();
const notifyConfig = ref({
	text: '',
	type: '',
});

const rules = reactive({
	username: [
		{
			required: true,
			message: '请输入用户名',
			trigger: ['blur', 'change'],
		}
	],
	password: [
		{
			required: true,
			message: '请输入密码',
			trigger: ['blur', 'change'],
		},
	],
	verifyCode: [
		{
			required: true,
			message: '请输入验证码',
			trigger: ['blur', 'change'],
		},
	],
});

onLoad(async () => {
	updateVerifyCode();

	load();
});

const updateVerifyCode = async () => {
	const res = await authService.getVerifyCode();
	verifyCodeUrl.value = `${res.data.data?.image}`;
	entity.value.verifyCodeKey = res.data.data?.key;
}

const load = async () => {
	const tmp = uni.getStorageSync(UNI_STORAGE_KEY_REMEMBER_ME);
	if (tmp) {
		const e = tmp;
		entity.value.username = e.username;
		entity.value.password = e.password;
	}
}

const showNotify = (config) => {
	notifyConfig.value = config;
	notify.value.show({
		type: config.type,
		message: config.message,
	});
}

const showError = (message) => {
	showNotify({ message: message, type: "error" });
}

const login = async () => {
	const formEl = formRef.value;
	loading.value = true;
	if (!formEl) {
		loading.value = false;
		return;
	}
	try {
		const valid = await formEl.validate();

		const res = await authService.login(entity.value);
		const authData = res.data.data;
		if (authData && authData.token) {
			const { token } = authData;
			uni.setStorageSync(UNI_STORAGE_KEY_TOKEN, token);

			const userProfile = await personalCenterService.retrieve();
			uni.setStorageSync(UNI_STORAGE_KEY_USER_PROFILE, userProfile);

			// warning: 此方式直接将用户名密码明文存入localStorage，并不安全
			// todo：寻找更合理方式实现“记住我”
			if (rememberMe.value) {
				uni.setStorageSync(UNI_STORAGE_KEY_REMEMBER_ME, {
					username: entity.value.username,
					password: entity.value.password,
				});
			} else {
				uni.removeStorageSync(UNI_STORAGE_KEY_REMEMBER_ME);
			}

			showNotify({ message: "登录成功", type: "success" });
			uni.switchTab({
				url: "/pages/home/home",
			});
		}
	} catch (err) {
		if (err.data && err.data.message) {
			showError(err.data && err.data.message);
		}

		updateVerifyCode();
		throw err;
	} finally {
		loading.value = false;
	}
};

const forgetPassword = () => {
	uni.navigateTo({
		url: `/pages/forget-password/forget-password?${entity.value.username ? "username=" + entity.value.username : ''}`,
	})
}

const register = () => {
	uni.navigateTo({
		url: '/pages/register/register',
	})
}
</script>

<style lang="scss"></style>